<template>
    <div class="StudentInfo">
        <el-scrollbar style="height: 100%">
            <div class="crumbs">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item>人员管理</el-breadcrumb-item>
                    <el-breadcrumb-item>学生管理</el-breadcrumb-item>
                    <el-breadcrumb-item>学生信息</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="container">
                <div class="handle-box">
                    <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                    <el-button type="primary" icon="el-icon-search" @click="search" style="margin-left: 10px;">搜索
                    </el-button>
                    <el-button icon="search" type="success" @click="add">新增<i
                            class="el-icon-circle-plus-outline el-icon--right"></i>
                    </el-button>
                    <el-button icon="search" type="danger" @click="showImport">Excel<i
                            class="el-icon-upload el-icon--right"></i>
                    </el-button>
                    <el-button type="text" @click="download">下载Excel示例</el-button>
                </div>
                <el-table :data="data" border max-height="500" class="table" ref="multipleTable" fit stripe
                    highlight-current-row @selection-change="handleSelectionChange">
                    <el-table-column type="selection" align="center"></el-table-column>
                    <el-table-column v-if='false' prop="id" label="id" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="classCode" label="classCode" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="region" label="region" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="updaycount" label="updaycount" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="userCode1" label="userCode1" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="userCode2" label="userCode2" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="classType" label="classType" sortable>
                    </el-table-column>
                    <el-table-column v-if='false' prop="card" label="card" sortable>
                    </el-table-column>
                    <el-table-column prop="date" width="120" label="日期" sortable>
                    </el-table-column>
                    <el-table-column prop="name" label="学生姓名">
                    </el-table-column>
                    <el-table-column prop="photo" label="照片">
                        <template slot-scope="scope">
                            <el-image style="width: 100%; height: 100%"
                                :src="`http://39.99.143.137:8000` + scope.row.photo" fit="fill"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="考勤状态" :formatter="formatter">
                        <template slot-scope="scope">
                            <span style="color: #00d1b2" v-if="scope.row.status == '在校'">{{scope.row.status}}</span>
                            <span style="color: #E6A23C" v-if="scope.row.status == '离校'">{{scope.row.status}}</span>
                            <span style="color: #409EFF" v-if="scope.row.status == '病假'">{{scope.row.status}}</span>
                            <span style="color: #F56C6C" v-if="scope.row.status == '缺勤'">{{scope.row.status}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sex" label="性别">
                    </el-table-column>
                    <el-table-column prop="theClass" label="班级">
                    </el-table-column>
                    <el-table-column prop="age" label="年龄">
                    </el-table-column>
                    <el-table-column prop="teacher" label="班主任">
                    </el-table-column>
                    <el-table-column label="操作" width="220" align="center" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-user" @click="parentEdit(scope.$index, scope.row)">家长
                            </el-button>
                            <el-button type="text" icon="el-icon-edit" class="org" @click="handleEdit(scope.$index, scope.row)">编辑
                            </el-button>
                            <el-button type="text" icon="el-icon-delete" class="red"
                                @click="handleDelete(scope.$index, scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="fenye">
                    <el-pagination @current-change="changePage" :page-size="pageSize" background layout="prev, pager, next" :total="total">
                    </el-pagination>
                </div>
            </div>
            <!-- 编辑框 -->
            <el-dialog title="修改学生信息" custom-class="editClass" width="60%" :visible.sync="editVisible"
                :close-on-press-escape="false" :close-on-click-modal="false">
                <v-editForm :getStudent="getStudent" @toggle-edit='toggleEdit' :editform="editform" :formLabelWidth="formLabelWidth" :dialogVisible="dialogVisible"
                    :getEditForm="getEditForm" :dialogImageUrl="dialogImageUrl" :schoolId="schoolId" :option="option" :label-position="labelPosition" :editVisible="editVisible">
                </v-editForm>
            </el-dialog>
            <!-- 新增框 -->
            <el-dialog title="添加学生信息" custom-class="editClass" width="60%" :visible.sync="addVisible"
                :close-on-press-escape="false" :close-on-click-modal="false">
                <v-addForm  :getStudent="getStudent" @toggle-add='toggleAdd' :formLabelWidth="formLabelWidth"
                    :option="option" :schoolId="schoolId" :label-position="labelPosition" :addVisible="addVisible" :schoolCode="schoolCode">
                </v-addForm>
            </el-dialog>
            <!-- 删除提示框 -->
            <el-dialog title="警告" :visible.sync="delVisible" width="400px" center>
                <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="delVisible = false">取 消</el-button>
                    <el-button type="primary" @click="deleteRow">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 导入excel -->
            <el-dialog title="批量导入" :visible.sync="importDialog" width="50%">
                <el-upload
                    accept=".xlsx"
                    :multiple='false'
                    :auto-upload='false'
                    :show-file-list='true'
                    :drag='true'
                    action='#'
                    :limit="1"
                    ref="newupload"
                    :on-exceed="handleExceed"
                    :before-upload="uploadFile" >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">一次只能上传一个文件，仅限text格式，单文件不超过1MB</div>
                </el-upload>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="importDialog = false">取 消</el-button>
                    <el-button type="primary" @click="newSubmitForm">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 家长右拉框 -->
            <el-drawer
                title="家长信息"
                :visible.sync="drawer"
                direction="rtl">
                <el-form>
                    <!-- 1 -->
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="姓名" label-width="120px">
                                <div v-if="false">{{parentForm1.userId}}</div>
                                <el-input v-model="parentForm1.userName" :disabled="inputStatus"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="手机号" label-width="120px">
                                <el-input v-model="parentForm1.phone" :disabled="inputStatus"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 2 -->
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="姓名" label-width="120px">
                                <div v-if="false">{{parentForm2.userId}}</div>
                                <el-input v-model="parentForm2.userName" :disabled="inputStatus"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="手机号" label-width="120px">
                                <el-input v-model="parentForm2.phone" :disabled="inputStatus"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="houtai-drawer__footer">
                    <el-button @click="drawer = false">取 消</el-button>
                    <el-button @click="parentUpdate" type="success">修改</el-button>
                    <el-button type="primary" @click="parentClose(id)">确定</el-button>
                </div>
            </el-drawer>
        </el-scrollbar>
    </div>
</template>
<script>
    import {
        GET_STUDENT,
        USER,
        DELETE_STUDENT,
        INSERT_STUDENT_BYEXCEL,
        FILEDOWN
    } from '@/api/api.js'
    import vEditForm from 'components/PersonManage/editForm.vue'
    import vAddForm from 'components/PersonManage/addForm.vue'
    import { mapState, mapGetters } from 'vuex'
    export default {
        name: 'StudentInfo',
        data() {
            return {
                tableData: [],
                imgName: '',
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                editVisible: false,
                addVisible: false,
                formLabelWidth: '120px',
                labelPosition: 'right',
                option: [{
                        label: '在校',
                        value: 0,
                    },
                    {
                        label: '离校',
                        value: 1,
                    },
                    {
                        label: '病假',
                        value: 2,
                    },
                    {
                        label: '缺勤',
                        value: 3,
                    }
                ],
                schoolCode: '', //学校编号
                classType: '', //班级类型
                // 编辑栏info start
                editform: {
                    id: '',
                    name: '',
                    photo: '',
                    status: '',
                    sex: '',
                    age: '',
                    teacher: '',
                    card: []
                },
                dialogImageUrl: '',
                dialogVisible: false,
                // end
                // 删除栏
                delVisible: false, 
                // end
                importDialog: false,
                fileList: [],
                pageNum: 1,
                total: 10,
                pageSize: 15,
                // 右拉框
                drawer: false,
                // 家长表单
                parentForm1: {},
                parentForm2: {},
                id: '',
                classType: '', // 班级类型
                // 输入框状态
                inputStatus: true,
                // 删除
                delId: ''
            }
        },
        components: {
            vEditForm,
            vAddForm
        },
        computed: {
            data() {
                return this.tableData.filter((d) => {
                    let is_del = false;
                    for (let i = 0; i < this.del_list.length; i++) {
                        if (d.name === this.del_list[i].name) {
                            is_del = true;
                            break;
                        }
                    }
                    if (!is_del) {
                        if (d.status.indexOf(this.select_cate) > -1 && (d.name.indexOf(this.select_word) > -1 ||
                            d.status.indexOf(this.select_word) > -1)) {
                            return d;
                        }
                    }
                })
            },
            ...mapState({
                schoolId: state => state.schoolId,
                classId: state => state.classId
            })
        },
        created() {
            this.schoolCode = Number(this.schoolId)
        },
        mounted() {
            setTimeout(() => {
                this.getStudent()
            }, 100);
        },
        methods: {
            toggleEdit(val){
                this.editVisible = val
            },
            toggleAdd(val){
                this.addVisible = val
            },
            /**
             * @desc 获取学生信息
             * @param {
             *      current: Number 当前页
             *      size: Number    每页个数
             * }
             */
            async getStudent() {
                let that = this
                console.log(this.classId)
                await that.$GET(`${GET_STUDENT}`, {
                    current: parseInt(that.pageNum),
                    size: Number(that.pageSize),
                    schoolId: this.schoolId,
                    classId: this.classId
                })
                    .then(res => {
                        if (res.code == 200) {
                            var data = []
                            that.total = res.data.total
                            let _res = res.data.records
                            for (let i = 0; i < _res.length; i++) {
                                var obj = {}
                                obj.id = _res[i].id == null ? '暂无数据' : _res[i].id
                                obj.date = that.$moment(_res[i].date).format("YYYY MMM Do")
                                obj.name = _res[i].name == null ? '暂无数据' : _res[i].name
                                obj.photo = `${_res[i].photo}`
                                obj.theClass = _res[i].clazz.className == null ? '-': _res[i].clazz.className
                                obj.status = that.judgeStatus(_res[i].status)
                                obj.sex = that.judgeSex(_res[i].sex)
                                obj.age = _res[i].age == null ? '暂无数据' : _res[i].age
                                obj.teacher = _res[i].teacher == null ? '暂无数据' : _res[i].teacher
                                obj.classCode = _res[i].classCode
                                obj.userCode1 = _res[i].userCode1,
                                obj.userCode2 = _res[i].userCode2,
                                obj.classType = _res[i].classCode,
                                obj.card = _res[i].cardList
                                data[i] = obj
                            }
                            that.tableData = data
                        } else if(res.code == 401) {
                            that.$message.error(res.msg)
                            // setTimeout(() => {
                            //     this.$router.push({path: '/'})
                            // }, 500);
                        }
                    })
            },
            formatter(row, column) {
                return row.status;
            },
            search() {
                this.is_search = true;
            },
            add() {
                this.addVisible = true;
            },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = parseInt(val);
                this.getInvestList();
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            // 学生编辑
            handleEdit(index, row) {
                this.editform = row;
                this.editVisible = true
            },
            // 右拉框
            async parentEdit(index, row) {
                this.drawer = true
                let code1 = row.userCode1
                let code2 = row.userCode2
                this.id = row.id
                this.classType = row.classType
                await this.$GET(`${USER}`,{
                    userCode1: code1,
                    userCode2: code2,
                })
                .then(res => {
                    this.parentForm1 = res.data[0]
                    this.parentForm2 = res.data[1]
                })
            },
            // 右拉框--修改生效
            parentUpdate() {
                this.inputStatus = false
            },
            /**
             * @desc 右拉框--确定
             * @param {
             *      studentId, userId, phone, userName
             * }
             */
            async parentClose(id) {
                let param = [
                    {
                        studentId: this.id,
                        userId: this.parentForm1.userId,
                        phone: this.parentForm1.phone,
                        userName: this.parentForm1.userName,
                        classType: this.classType
                    },
                    {
                        studentId: this.id,
                        userId: this.parentForm2.userId,
                        phone: this.parentForm2.phone,
                        userName: this.parentForm2.userName,
                        classType: this.classType
                    }
                ]
                for(let i = 0; i < param.length; i++) {
                    await this.$PUT(`${USER}`, param[i])
                    .then(res=> {
                        try {
                            if(res.code == 200) {
                                this.drawer = false
                                this.$message.success(res.msg)
                            } else {
                                this.$message.fail(res.msg)
                            }
                        } catch (error) {
                            console.log(error)
                        } finally {
                            this.drawer = false
                        }
                        
                    })
                }
                this.getStudent()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 性别判断
            judgeSex(sex) {
                switch (sex) {
                    case 1:
                        return '男'
                        break;
                    case 2:
                        return '女'
                        break;
                    case '男':
                        return 1
                        break;
                    case '女':
                        return 2
                        break;
                }
            },
            // 考勤判断
            judgeStatus(status) {
                switch (status) {
                    case 0:
                        return '在校'
                        break;
                    case 1:
                        return '离校'
                        break
                    case 2:
                        return '病假'
                        break
                    case 3:
                        return '缺勤'
                        break
                    case '在校':
                        return 0
                        break;
                    case '离校':
                        return 1
                        break
                    case '病假':
                        return 2
                        break
                    case '缺勤':
                        return 3
                        break
                }
            },
            
            // 显示导入弹窗
            showImport() {
                this.importDialog = true
            },
            // 上传文件个数超过定义的数量
            handleExceed (files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
            },
            // 上传文件
            async uploadFile(file) {
                let fd = new FormData()
                fd.append('excel',file);
                fd.append('schoolId',this.schoolId);
                await this.$POST(`${INSERT_STUDENT_BYEXCEL}`,fd)
                    .then(res => {
                        if(res.code == 200) {
                            this.$notify({
                                title: '成功',
                                message: `${res.msg}`,
                                type: 'success'
                            });
                            this.importDialog = false
                        } else {
                            this.$notify({
                                title: '失败',
                                message: `上传失败`,
                                type: 'fail'
                            });
                            this.importDialog = false
                        }
                    })
            },
            newSubmitForm(){//确定上传
                this.$refs.newupload.submit();
            },
            // 删除现在
            async deleteRow() {
                let that = this
                let Did = Number(that.delId)
                let formData = new FormData()
                formData.append("id", Did)
                await that.$POST(`${DELETE_STUDENT}`, formData)
                .then(res => {
                    if(res.code == 200) {
                        that.$message.success(res.msg)
                        that.delVisible = false
                        that.getStudent()
                    } else {
                        that.$message.fail(res.msg)
                    }
                })
            },
            // 删除按钮
            handleDelete(index, row) {
                this.delVisible = true
                this.delId = row.id
            },
            delAll() {
                const length = this.multipleSelection.length;
                let str = '';
                this.del_list = this.del_list.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error('删除了' + str);
                this.multipleSelection = [];
            },
            setImgName(file, fileList) {},
            // 获取当前页码
            changePage(val) {
                this.pageNum = parseInt(val);
                this.getStudent(); 
            },
            // 下载Excel
            download() {
                window.open(`${FILEDOWN}`)
            },
            // 监听编辑框 卡号管理
            getEditForm() {
                this.editVisible = false
            }
        }
    }
</script>
<style lang="scss">
    .handle-box {
        margin-bottom: 20px;
    }

    .fenye {
        text-align: right;
        margin:15px auto;
        padding-left: 150px;
        width: 60%;
        padding-bottom: 35px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .red {
        color: #F56C6C;
    }
    .org {
        color: #E6A23C;
    }

    .red:hover,
    .red:focus {
        color: #ff8686;
    }
    .org:hover,
    .org:focus {
        color: #fccd88;
    }


    .page-component__scroll .el-scrollbar__wrap {
        overflow-x: hidden;
    }

    .editClass {
        padding-right: 5%;
    }
    .del-dialog-cnt {
        font-size: 16px;
        text-align: center
    }
    .houtai-drawer__footer {
        text-align: center;
    }
</style>